package com.example.websocket.controller;

import com.example.websocket.entity.Group;
import com.example.websocket.entity.GroupMessage;
import com.example.websocket.entity.User;
import com.example.websocket.service.IGroupMessageService;
import com.example.websocket.service.IGroupService;
import com.example.websocket.service.impl.GroupMessageServiceImpl;
import com.example.websocket.service.impl.GroupServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class GroupController {
    @Autowired
    IGroupService groupService;

    @Autowired
    IGroupMessageService groupMessageService;

    @GetMapping("/toAddGroupPage")
    public String toAddGroupPage(){
        return "addGroup";
    }

    @GetMapping("/group/{groupid}")
    public String toGroupRoom(@PathVariable("groupid") int groupid, Model model,HttpSession session)
    {
        Group group = groupService.selectByPrimaryKey(groupid);
        List<GroupMessage> recent = groupMessageService.getRecent(groupid);
        model.addAttribute("group",group);
        model.addAttribute("recentMessage",recent);
        model.addAttribute("userid",((User)session.getAttribute("user")).getId());
        return "groupRoom";
    }

    @PostMapping("/group")
    public String addGroupe(Group group, HttpSession session){
        Group group1 = new Group();
        group1.setGname(group.getGname());
        group1.setCreatetime(new Date());
        group1.setCreateUserid(((User)session.getAttribute("user")).getId());
        groupService.insert(group1);
        return "redirect:/space";
    }

    @DeleteMapping("/group/{id}")
    public String deleteGroupe(@PathVariable("id") int id){
        groupService.deleteByPrimaryKey(id);
        return "redirect:/space";
    }

}
